/**
 * 
 */
package neptune.web.server.operations;

import it.robertobifulco.ias.IncorrectParamsException;
import it.robertobifulco.ias.Operation;

import java.util.ArrayList;

import neptune.manager.NeptuneManager;
import neptune.manager.connector.Connector;
import neptune.manager.model.cluster.Cluster;
import neptune.manager.model.cluster.PhysicalNode;
import neptune.manager.model.experiment.Experiment;
import neptune.web.server.ApplicationManager;

/**
 * @author Roberto Bifulco [RobertoBifulco.it] [info@robertoBifulco.it]
 * 
 */
public class GetAllocatedNodes implements Operation {

	public static String ID = "GetAllocatedNodes";

	/*
	 * (non-Javadoc)
	 * 
	 * @see it.robertobifulco.ias.Operation#execute(java.lang.Object[])
	 */
	public Object[] execute(Object[] args) throws IncorrectParamsException,
			Exception {

		String expId = (String) args[0];

		Cluster cluster = ApplicationManager.getApplicationManager()
				.getNeptuneManager().getCluster();
		Experiment exp = ApplicationManager.getApplicationManager()
				.getNeptuneManager().getExperiment(expId);

		ArrayList<String[]> vmInfos = new ArrayList<String[]>(0);

		for (PhysicalNode machine : cluster.getNodes()) {
			boolean containsExpNode = false;

			String[] hostedNodes = machine.getHostedNodes();
			for (String node : hostedNodes) {
				if (NeptuneManager.getExpNameFromNodeFullID(node) == null)
					continue;
				if (NeptuneManager.getExpNameFromNodeFullID(node).equals(expId)) {
					containsExpNode = true;
					break;
				}
			}

			if (containsExpNode) {
				String[][] domains;
				Connector connector = null;
				try {

					connector = ApplicationManager.getApplicationManager()
							.getNeptuneManager().getConnector(machine.getId());

					domains = connector.getAllDomains();

				} catch (Exception e) {
					domains = new String[][] {};
				}

				for (String[] domain : domains) {
					if (NeptuneManager.getExpNameFromNodeFullID(domain[1]) == null)
						continue;
					if (NeptuneManager.getExpNameFromNodeFullID(domain[1])
							.equals(expId)) {

						String nodeId = NeptuneManager
								.getNodeNameFromNodeFullID(domain[1]);
						String nodeStatus = domain[2];
						String nodeControlAddress = exp.getTopology()
								.searchNodeIntoTopology(nodeId)
								.getControlAddress().getAddress();

						vmInfos.add(new String[] { nodeId, nodeStatus,
								nodeControlAddress });

					}
				}

				if (connector != null)
					connector.closeConnection();
			}
		}

		return new Object[] { vmInfos.toArray(new String[][] {}) };
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see it.robertobifulco.ias.Operation#getDescription()
	 */
	public String getDescription() {
		return "Gets the allocated nodes status for an experiment";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see it.robertobifulco.ias.Operation#getID()
	 */
	public String getID() {
		return ID;
	}

}
